package cn.wlinker.video.monitor.brand.hikversion.create;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import cn.wlinker.video.monitor.brand.hikversion.dto.HikISecureDeviceModel;
import cn.wlinker.video.monitor.domain.Page;
import cn.wlinker.video.monitor.domain.PageQuery;
import cn.wlinker.video.monitor.domain.dto.MonitorDeviceDTO;
import cn.wlinker.video.monitor.domain.dto.PlayUrlDTO;
import cn.wlinker.video.monitor.domain.vo.MonitorDeviceVO;
import cn.wlinker.video.monitor.domain.vo.PictureUrlVO;
import cn.wlinker.video.monitor.domain.vo.VideoVO;
import cn.wlinker.video.monitor.service.IVideoStreamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 海康综合安防平台获取视频流
 *
 * @author gxsjx
 * @version 1.0
 * @date 2022/7/25
 */
@Slf4j
@Service
public class ISecureStreamServiceImpl implements IVideoStreamService {

    /**
     * 设置主机地址
     */
    @Value("${hik-config.media.host}")
    public void setHost(String host) {
        ArtemisConfig.host = host;
    }

    /**
     * 设置 key
     */
    @Value("${hik-config.media.appKey}")
    public void setAppKey(String appKey) {
        ArtemisConfig.appKey = appKey;
    }

    /**
     * 设置 sk
     */
    @Value("${hik-config.media.appSecret}")
    public void setAppSecret(String appSecret) {
        ArtemisConfig.appSecret = appSecret;
    }

    /**
     * 能力开放平台的网站路径
     */
    private static final String ARTEMIS_PATH = "/artemis";

    @Override
    public VideoVO buildVideoStream(MonitorDeviceDTO dto, PlayUrlDTO playUrlDTO) {
        VideoVO vo = new VideoVO();
        String stream = dto.getVideoStreamFormat();
        if (StringUtils.isEmpty(stream)) {
            stream = "hls";
        }
        if (!("hls".equals(stream) || "flv".equals(stream))) {
            stream = "hls";
        }
        String cameraIndexCode = dto.getDeviceCode();
        final String getCamsApi = ARTEMIS_PATH + "/api/video/v1/cameras/previewURLs";
        Map<String, String> path = new HashMap<>(2);
        path.put("https://", getCamsApi);
        JSONObject jsonBody = new JSONObject();
        jsonBody.putOpt("cameraIndexCode", cameraIndexCode);
        jsonBody.putOpt("streamType", "1");
        jsonBody.putOpt("protocol", stream);
        jsonBody.putOpt("transmode", "1");
        jsonBody.putOpt("expand", "transcode=1&videotype=h264");
        String body = jsonBody.toString();
        // post请求application/json类型参数
        try {
            String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json", null);
            // 数据解析
            JSONObject jsonObject = JSONUtil.parseObj(result);
            Object data = jsonObject.get("data");
            String jsonString = JSONUtil.toJsonStr(data);
            JSONObject object = JSONUtil.parseObj(jsonString);
            String url = object.get("url").toString();
            vo.setPlayUrl(url);
        } catch (RuntimeException e) {
            log.error("构建视频流异常", e);
            vo.setPlayUrl("");
        }
        return vo;
    }

    @Override
    public Page<MonitorDeviceVO> getMonitorDeviceList(String deviceCode, String status, PageQuery pageQuery) {
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/camera/advance/cameraList";
        Map<String, String> path = new HashMap<>(2);
        path.put("https://", getCamsApi);
        JSONObject jsonBody = new JSONObject();
        jsonBody.putOpt("pageNo", 1);
        jsonBody.putOpt("pageSize", 1000);
        String body = jsonBody.toString();
        // post请求application/json类型参数
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json", null);
//        log.info("返回的数据 --> {}", result);
        List<HikISecureDeviceModel> hikISecureDeviceModels = decodeHikVisionResponseData(result);
        List<MonitorDeviceVO> collect = hikISecureDeviceModels.stream()
                .map(t -> {
                            MonitorDeviceVO monitorDeviceVO = new MonitorDeviceVO();
                            monitorDeviceVO.setName(t.getCameraName());
                            monitorDeviceVO.setStatus(t.getStatus());
                            monitorDeviceVO.setDeviceCode(t.getCameraIndexCode());
                            monitorDeviceVO.setChannelNo(t.getChannelNo());
                            monitorDeviceVO.setCameraType(t.getCameraType());
                            monitorDeviceVO.setCameraTypeName(t.getCameraTypeName());
                            monitorDeviceVO.setRegionIndexCode(t.getRegionIndexCode());
                            return monitorDeviceVO;
                        }
                ).collect(Collectors.toList());
        Page<MonitorDeviceVO> build = pageQuery.build();
        build.setRecords(collect);
        return build;
    }

    @Override
    public PictureUrlVO capture(MonitorDeviceDTO dto, Integer quality) {
        return null;
    }

    /**
     * 解析综合安防平台返回的数据
     *
     * @param result
     */
    public List<HikISecureDeviceModel> decodeHikVisionResponseData(String result) {
        // 返回数据解析
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (!"0".equals(jsonObject.get("code"))) {
            throw new RuntimeException(jsonObject.get("code").toString());
        }
        Object data = jsonObject.get("data");
        JSONObject jsonObject1 = JSONUtil.parseObj(JSONUtil.toJsonStr(data));
        Object list = jsonObject1.get("list");
        List<HikISecureDeviceModel> hikISecureDeviceModels = JSONUtil.toList(JSONUtil.parseArray(list), HikISecureDeviceModel.class);
        log.info("我能获取到的监控列表信息 --> {}", JSONUtil.toJsonStr(hikISecureDeviceModels));
        return hikISecureDeviceModels;
    }
}
